package com.wangxiaonan.berry.controller;

import com.alibaba.fastjson.JSONObject;
import com.wangxiaonan.berry.entity.BaiQiShi;
import com.wangxiaonan.berry.handler.ResponseWrapper;
import com.wangxiaonan.berry.service.BaiQiShiService;
import javax.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

/**
 * 白骑士 https://www.baiqishi.com/
 *
 * @Author: wangxiaonan
 * @Date: 2019/7/2
 **/
@CrossOrigin
@RestController
@RequestMapping("/baiqishi")
public class BaiQiShiController {

    private static final Logger logger = LoggerFactory.getLogger(BaiQiShiController.class);

    @Resource
    private BaiQiShiService baiQiShiService;

    @RequestMapping(value = "/query", method = RequestMethod.POST)
    public ResponseWrapper query(@RequestBody BaiQiShi baiQiShi) {
        String data = baiQiShiService.query(baiQiShi);
        return getResponseWrapper(data);
    }

    @RequestMapping(value = "/queryHistory", method = RequestMethod.POST)
    public ResponseWrapper queryHistory(@RequestBody BaiQiShi baiQiShi) {
        String data = baiQiShiService.queryHistory(baiQiShi);
        return getResponseWrapper(data);
    }

    private ResponseWrapper getResponseWrapper(String data) {
        logger.info("白骑士返回参数：{}", data);
        JSONObject result = JSONObject.parseObject(data);
        ResponseWrapper wrapper = new ResponseWrapper();
        String resultCode = result.getString("resultCode");
        if ("BQS000".equals(resultCode)) {
            JSONObject resultData = result.getJSONObject("resultData");
            wrapper.success().setData(resultData);
        } else {
            String resultDesc = result.getString("resultDesc");
            wrapper.fail(resultCode).setMessage(resultDesc);
        }
        return wrapper;
    }
}
